/*
** Copyright (c) 2008 Mobile GCalendarManager
**
** Permission is hereby granted, free of charge, to any person
** obtaining a copy of this software and associated documentation
** files (the "Software"), to deal in the Software without
** restriction, including without limitation the rights to use,
** copy, modify, merge, publish, distribute, sublicense, and/or sell
** copies of the Software, and to permit persons to whom the
** Software is furnished to do so, subject to the following
** conditions:
**
** The above copyright notice and this permission notice shall be
** included in all copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
** OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
** NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
** HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
** WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
** FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
** OTHER DEALINGS IN THE SOFTWARE.
*/

/**
 *
 */
package au.edu.mq.comp.itec800.mgc.ui.cli.commands;

import java.io.IOException;
import java.util.List;

import org.apache.log4j.Logger;

import au.edu.mq.comp.itec800.mgc.lib.calendar.event.NotificationInterval;
import au.edu.mq.comp.itec800.mgc.ui.cli.ICommand;
import au.edu.mq.comp.itec800.mgc.util.CommandUtils;
import au.edu.mq.comp.itec800.mgc.util.MGCUtils;
import au.edu.mq.comp.itec800.mgc.util.Utils;

import com.google.gdata.data.calendar.CalendarEventEntry;
import com.google.gdata.data.extensions.Reminder;
import com.google.gdata.data.extensions.Reminder.Method;
import com.google.gdata.util.ServiceException;

/**
 * Notification-context management class.
 *
 * @author Laurent Malvert [laurent.malvert@students.mq.edu.au]
 */
public enum NotificationCommand implements ICommand
{
  add
  {
    @Override
    public boolean              execute(final String ... args)
    {
      boolean                   succeeded = false;
      final CalendarEventEntry  evt       = MGCUtils.getGAccount()
                                            .getCalendarManager()
                                            .getEventManager()
                                            .getCurrentEvent().getEvent();
      Reminder                  rem       = new Reminder();
      Method                    mth       = null;

      mth = Method.valueOf(Method.class,
                           MGCUtils.query(" >> Method: ", 0, args).toUpperCase());
      if (mth != null)
      {
        try
        {
          int min;
          int minBefore = -1;

          min = Integer.parseInt(MGCUtils.query(" >> Minutes Before: ", 1, args));
          for (NotificationInterval iv : NotificationInterval.values())
          {
            if (min == iv.toInt())
            {
              minBefore = min;
              break;
            }
            if (min > iv.toInt())
              minBefore = iv.toInt();
          }
          rem.setMinutes(minBefore);
          rem.setMethod(mth);
          evt.getReminder().add(rem);
          evt.update();
          MGCUtils.getGAccount().getCalendarManager().getEventManager().update();
          succeeded = true;
          //TODO: print success
        }
        catch (NumberFormatException e)
        {
          MGCUtils.getConsole().getIO().output("[ERROR] Invalid Number.");
        }
        catch (IOException e)
        {
          logger.debug(e.getMessage(), e);
        }
        catch (ServiceException e)
        {
          logger.debug(e.getMessage(), e);
        }
      }
      else
      {
        int idx = 0;
        MGCUtils.getConsole().getIO().output("[ERROR] Invalid Method. "
                                             + "Available are: ");
        for (Method m : Method.values())
        {
          if (idx++ > 0)
            MGCUtils.getConsole().getIO().output(", ");
          MGCUtils.getConsole().getIO().output(m.name());
        }
      }
      return (succeeded);
    }
  },
  edit
  {
    @Override
    public boolean  execute(final String ... args)
    {
      return (false);
    }
  },
  help
  {
    @Override
    public boolean  execute(final String ... args)
    {
      return (false);
    }
  },
  list
  {
    @Override
    public boolean              execute(final String ... args)
    {
      boolean                   succeeded = false;
      final CalendarEventEntry  evt       = MGCUtils.getGAccount()
                                            .getCalendarManager()
                                            .getEventManager()
                                            .getCurrentEvent().getEvent();
      final StringBuffer        out       = new StringBuffer(512);
      int                       idx       = 0;
      List<Reminder>            rems;

      rems  = evt.getReminder();
      if (rems.size() > 0)
      {
        for (Reminder r : rems)
        {
          out.append(String.format("%2d. %s %d\n",
                                   idx++, r.getMethod(), r.getMinutes()));
        }
      }
      else
        out.append("\t None.\n");
      MGCUtils.getConsole().getIO().output(out.toString());
      return (succeeded);
    }
  },
  noop
  {
    @Override
    public boolean  execute(final String ... args)
    {
      return (true);  //  does nothing but does it well
    }
  },
  remove
  {
    @Override
    public boolean  execute(final String ... args)
    {
      boolean                   succeeded = false;

      if (args.length > 0)
      {
        try
        {
          final CalendarEventEntry  evt       = MGCUtils.getGAccount()
                                                .getCalendarManager()
                                                .getEventManager()
                                                .getCurrentEvent().getEvent();
          final int                 idx       = Integer.parseInt(args[0]);
          final List<Reminder>      rems      = evt.getReminder();

          if (Utils.isInBound(rems, idx))
          {
            rems.remove(idx);
            evt.update();
            MGCUtils.getGAccount().getCalendarManager().getEventManager().update();
            succeeded = true;
            //TODO: print something
          }
        }
        catch (NumberFormatException e)
        {

        }
        catch (IOException e)
        {
          logger.debug(e.getMessage(), e);
        }
        catch (ServiceException e)
        {
          logger.debug(e.getMessage(), e);
        }
      }
      return (succeeded);
    }
  },
  view
  {
    @Override
    public boolean  execute(final String ... args)
    {
      return (false);
    }
  };

  public boolean  execute(final String ... args)
  {
    return (false);
  }

  public boolean  needsAuthentication()
  {
    return (false);
  }

  public ICommand         getMaster()
  {
    return (null);
  }

  public boolean          isAlias()
  {
    return (false);
  }

  public ICommand         getTopMaster()
  {
    return (CommandUtils.getTopMaster(this));
  }

  public String   help()
  {
    return ("");
  }

  private static final Logger  logger = Logger.getLogger(NotificationCommand.class);
}
